using System;
using System.Collections;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace ZSW.Framework.Utils
{
    // 读取Csv数据
    public static class ZSWFUtil_CsvReader
    {
        private static Coroutine m_loadDataCoroutine;

        public static void ReadCsvSync(string path, Action<string[]> callback)
        {
            // 避免重复加载
            if (m_loadDataCoroutine != null)
            {
                CoroutineRunner.StopCoroutine(m_loadDataCoroutine);
            }
            m_loadDataCoroutine = CoroutineRunner.StartCoroutine(getCsvData(path, callback));
        }

        // 获取Csv数据（同步版本）
        public static string[] ReadCsv(string path)
        {
            try
            {
                // 使用File.ReadAllText同步读取CSV文件内容
                string csvData = File.ReadAllText(path, Encoding.UTF8);

                // 处理UTF-8 BOM
                csvData = csvData.TrimStart('\ufeff');

                // 将CSV内容按换行符分割成字符串数组
                return csvData.Split(new[] { "\n" }, StringSplitOptions.None);
            }
            catch (IOException ex)
            {
                ZSWFUtil_Debug.Log("CsvReader", $"Failed to read CSV file: {ex.Message}");
                return null; // 或者返回一个空数组，取决于您的业务需求
            }
        }


        // 获取Csv数据
        private static IEnumerator getCsvData(string path, Action<string[]> callback)
        {
            using (UnityWebRequest www = UnityWebRequest.Get(path))
            {
                yield return www.SendWebRequest();

                if (www.result != UnityWebRequest.Result.Success)
                {
                    ZSWFUtil_Debug.Log("CsvReader", www.error);
                }
                else
                {
                    string csvData = www.downloadHandler.text;
                    // 数据类型可能为UTF-8 BOM 此时需要去除BOM头
                    csvData = csvData.TrimStart('\ufeff');
                    callback?.Invoke(csvData.Split("\n"));
                }
            }
        }
    }
}
